<?php
declare (strict_types = 1);

namespace app\controller\admin;

use app\event\AdminActionEvent;
use app\traits\MyControllerTrait;
use Symfony\Component\EventDispatcher\EventDispatcher;
use think\facade\Session;
use think\Request;
use app\model\AdminPermission;
use app\model\AdminRolePermission;
use think\facade\Db;
use think\facade\Log;
use app\model\AdminRole;

class AdminRolePermissionController
{
    use MyControllerTrait;

    protected string $title = "角色权限";
    protected string $uri   = '/admin/role-permission';

    public function index(Request $request)
    {
        $admin_role_id = $request->get('admin_role_id', '0');
        $data = [
            'title'         => $this->title,
            'uri'           => $this->uri,
            'admin_role_id' => $admin_role_id
        ];
        return view($this->uri.'/'.__FUNCTION__, $data);
    }// index() end

    // 获取角色权限
    public function show(Request $request)
    {
        $admin_role_id   = (int)$request->get('admin_role_id', 0);
        $role_permission = AdminRolePermission::getRolePermissionFromCache($admin_role_id);
        $data = [
            'code'      => 1,
            'message'   => 'success',
            'data'      => $role_permission
        ];
        return json($data);
    }// show() end

    // 保存角色权限
    public function store(Request $request)
    {
        $data          = $request->post('package');
        $admin_role_id = (int)$request->post('admin_role_id', 0);
        // Log::channel('admin-controller')->info($data);

        if (1 > $admin_role_id) return json(['code' => 1, 'message' => "角色权限 ID:{$admin_role_id} 不存在"]);
        $role = AdminRole::whereRaw("id = :id", ['id' => $admin_role_id])->findOrEmpty();
        if ($role->isEmpty()) return json(['code' => 0, 'message' => "角色权限 ID:{$admin_role_id} 不存在"]);

        Db::startTrans();
        try {
            // 清空旧的角色权限
            AdminRolePermission::whereRaw("admin_role_id = :id", ['id' => $admin_role_id])->delete();

            // 写入新的角色权限
            foreach($data as $permission)
            {
                //dump($permission);
                AdminRolePermission::generateLog($admin_role_id, (int)$permission['id']);
                $children = $permission['children'] ?? [];
                foreach($children as $child)
                {
                    AdminRolePermission::generateLog($admin_role_id, (int)$child['id']);
                }
            }
            // 如果当前登录的用户的角色 id = session 里的角色 id，设置角色权限 ID
            if (Session::get('admin_user.admin_role_id') == $admin_role_id) AdminRolePermission::setPermissionIdsForSession($admin_role_id);

            Db::commit();
        } catch (\Exception $e){
            Db::rollback();

            $message = [
                'function'  => __CLASS__.'->'.__FUNCTION__.'():'.__LINE__,
                'error'     => $e->getMessage()
            ];
            Log::channel('admin-controller')->error(json_encode($message, JSON_UNESCAPED_UNICODE));
            return json(['code' => 0, 'message' => '失败']);
        }
        $data = [
            $this->getPermissionTitle($this->uri.'/'.__FUNCTION__),
            Session::get("admin_user.account"),
            $role->title
        ];
        (new EventDispatcher)->dispatch((new AdminActionEvent($request, $data)), AdminActionEvent::EVENT_NAME);

        AdminRolePermission::setRolePermissionToCache(AdminPermission::getPermission());
        return json(['code' => 1, 'message' => '成功']);
    }// store() end
}
